package com.qdlc.p2p.biz.executer.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.executer.BaseExecuter;
import com.qdlc.p2p.biz.service.ExperienceBorrowService;
import com.qdlc.p2p.biz.service.ExperienceCollectionService;
import com.qdlc.p2p.biz.service.ExperienceRuleService;
import com.qdlc.p2p.biz.service.ExperienceService;
import com.qdlc.p2p.biz.service.ExperienceTenderService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.Experience;
import com.qdlc.p2p.dal.dto.ExperienceBorrow;
import com.qdlc.p2p.dal.dto.ExperienceRule;
import com.qdlc.p2p.dal.dto.ExperienceTender;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.ExperienceModel;
import com.qdlc.p2p.dal.model.ExperienceRuleModel;
import com.qdlc.p2p.dal.model.ExperienceTenderModel;

@Service
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ExperienceExecuter extends BaseExecuter {
	
	private UserService userService;
	
	private ExperienceService experienceService;
	private ExperienceRuleService experienceRuleService;
	private ExperienceBorrowService experienceBorrowService;
	private ExperienceTenderService experienceTenderService;
	private ExperienceCollectionService experienceCollectionService;
	
	/**
	 * 获取（启用的）体验券规则
	 * @return
	 */
	public List<ExperienceRule> findUsableExperienceRule() {
		experienceRuleService = (ExperienceRuleService) BeanUtil.getBean("experienceRuleService");
		return experienceRuleService.findUsableExperienceRule();
	}
	
	/**
	 * 获取用户（所有的)体验券
	 * @param userId
	 */
	public PageDataList<ExperienceModel> findExperience(long userId) {
		experienceService = (ExperienceService) BeanUtil.getBean("experienceService");
		return experienceService.findExperience(userId);
	}
	
	/**
	 * 获取用户（可用的)体验券数量
	 * @param userId
	 */
	public int countUsableExperience(long userId){
		experienceService = (ExperienceService) BeanUtil.getBean("experienceService");
		return experienceService.countUsableExperience(userId);
	}
	
	/**
	 * 获取用户（可用的)体验券
	 * @param userId
	 */
	public List<Experience> findUsableExperience(long userId){
		experienceService = (ExperienceService) BeanUtil.getBean("experienceService");
		return experienceService.findUsableExperience(userId);
	}
	
	/**
	 * 获取投资人可使用体验券投标最大额度
	 * @param borrow
	 * @param tenderUserId
	 * @return
	 */
	public Map<String, Object> findCanTenderExperienceAmount(Borrow borrow, long tenderUserId){
		if(borrow != null){
			Map<String, Object> map = new HashMap<String, Object>();
			double mostExperience = 0;
			double mostExperienceSingle = 0;
			double borrowTenderUseExperience = 0;
			double borrowTenderUseExperienceSingle = 0;
			double canUseExperienceMoney = 0;
			boolean canUseExperience = false;
			
			experienceBorrowService = (ExperienceBorrowService) BeanUtil.getBean("experienceBorrowService");
			ExperienceBorrow experienceBorrow = experienceBorrowService.findByBorrow(borrow.getId());
			if(experienceBorrow != null) {
				mostExperience = experienceBorrow.getMostExperience();
				mostExperienceSingle = experienceBorrow.getMostExperienceSingle();
				experienceTenderService = (ExperienceTenderService) BeanUtil.getBean("experienceTenderService");
				borrowTenderUseExperience = experienceTenderService.sumExperienceCapital(borrow.getId(), ExperienceTenderModel.EXPERIENCE_TENDER_STATUS_PENDING);
				borrowTenderUseExperienceSingle = experienceTenderService.sumExperienceCapital(tenderUserId, borrow.getId(), ExperienceTenderModel.EXPERIENCE_TENDER_STATUS_PENDING);
				
				double dvalue = mostExperience - borrowTenderUseExperience;
				double dvalueSingle = mostExperienceSingle - borrowTenderUseExperienceSingle;
				canUseExperienceMoney = dvalueSingle < dvalue ? dvalueSingle : dvalue ;
				
				canUseExperience = true;
			}
			map.put("canUseExperience", canUseExperience);
			map.put("canUseExperienceMoney", canUseExperienceMoney);
			return map;
		}
		return null;
	}
	
	/**
	 * 发放体验券
	 * @param userId
	 * @param experienceRuleId
	 */
	public Experience giveExperience(long userId, long experienceRuleId) throws Exception {
		experienceRuleService = (ExperienceRuleService) BeanUtil.getBean("experienceRuleService");
		ExperienceRule experienceRule = experienceRuleService.findById(experienceRuleId);
		ExperienceRuleModel experienceRuleModel = new ExperienceRuleModel();
		// 体验券规则校验
		boolean checkResult = experienceRuleModel.checkForGiveExperience(experienceRule);
		if (!checkResult) {
			return null;
		}
		// 发放体验券
		userService = (UserService) BeanUtil.getBean("userService");
		User user = userService.find(userId);
		if(user==null){
			throw new UserException("该用户不存在，体验券发放失败！");
		}
		Experience experience = new Experience();
		experience.setUserId(user.getUserId());
		experience.setExperienceRuleId(experienceRule.getId());
		experience.setAmount(experienceRule.getAmount());
		experience.setValidTime(experienceRule.getValidTime());
		experience.setStatus(ExperienceModel.EXPERIENCE_STATUS_UNUSED);
		experience.setAddTime(DateUtil.getNow());
		experience.setExpiredTime(DateUtil.rollDay(experience.getAddTime(), experienceRule.getValidTime()));
		experienceService = (ExperienceService) BeanUtil.getBean("experienceService");
		return experienceService.save(experience);
	}
	
	/**
	 * 获取待收体验券本金和利息
	 * @param borrowId
	 * @param period
	 * @return
	 */
	public Object[] getCapitalAndInterestByBorrowAndPeriod(long borrowId, int period){
		experienceService = (ExperienceService) BeanUtil.getBean("experienceService");
		return experienceService.getCapitalAndInterestByBorrowAndPeriod(borrowId, period);
	}
	
	/**
	 * 获取投标使用体验券金额
	 * 
	 * @param tenderId
	 * @return
	 */
	public double getTenderExperienceAmount(long tenderId) {
		experienceTenderService = (ExperienceTenderService) BeanUtil.getBean("experienceTenderService");
		return experienceTenderService.getTenderExperienceAmount(tenderId);
	}
	/**
	 * 获取投标使用体验券
	 * 
	 * @param tenderId
	 * @return
	 */
	public ExperienceTender getTenderExperience(long tenderId) {
		experienceTenderService = (ExperienceTenderService) BeanUtil.getBean("experienceTenderService");
		return experienceTenderService.getTenderExperience(tenderId);
	}
	
	/**
	 * 获取用户待收体验金本金金额
	 * 
	 * @param collectionId
	 * @return
	 */
	public double sumCollectionExperienceCapital(long collectionId) {
		experienceCollectionService = (ExperienceCollectionService) BeanUtil.getBean("experienceCollectionService");
		return experienceCollectionService.sumCollectionExperienceCapital(collectionId);
	}
	
	/**
	 * 获取用户待收体验金本金金额
	 * 
	 * @param collectionId
	 * @return
	 */
	public List<Object[]> getCollectionExperienceCapital(long collectionId) {
		experienceCollectionService = (ExperienceCollectionService) BeanUtil.getBean("experienceCollectionService");
		return experienceCollectionService.getCollectionExperienceCapital(collectionId);
	}
	
	/**
	 * 检测用户体验券的使用状态
	 * 
	 * @param experienceIds
	 * @param user
	 * @return
	 */
	public boolean checkExperience(long[] experienceIds, User user) {
		experienceService = (ExperienceService) BeanUtil.getBean("experienceService");
		return experienceService.checkExperience(experienceIds, user);
	}
}
